/**
 * Created by zxr on 16/11/11.
 */
var http = require('http');
var url = require('url');
var fs = require('fs');
var qs = require('querystring');
var items = [];
var server = http.createServer(function (req, res) {
	if (req.url == '/') {
		switch (req.method) {
			case 'POST':
				add(req, res);
				break;
			case 'GET':
				show(res);
				break;
			default :
				badRequest(res);
		}
	} else {
		notFind(res);
	}
});


function add(req, res) {
	var dat = '';
	req.setEncoding('utf8');
	req.on('data', function (thunk) {
		console.log(thunk)
		dat += thunk;
	});
	req.on('end', function () {
		var obj = qs.parse(dat);
		items.push(obj);
		console.log(items);
		show(res);
	});

}
function show(res) {
	var html = '<html><head><meta><title></title></head><body>'
		+ '<ul>'
		+ items.map(function(item){
			console.log(item);
				return '<li>' + item.name +'----'+ item.age + '</li>'
			}).join(' ')
		+ '</ul>'
		+ '<form action="/" method="post" enctype="application/x-www-form-urlencoded"> '
		+ '<P>姓名：<input type="text" name = "name"/></P>'
		+ '<P>年龄：<input type="text" name = "age"/></P>'
		+ '<P><input type="submit" value="提交"/></P>'
		+ '</form>'
		+ '</body>'
		+ '</html>';
	res.setHeader('Content-Type', 'text/html');
	res.setHeader('Content-Length', Buffer.byteLength(html));
	res.end(html);
}
function badRequest( res) {
	res.statusCode = 400;
	res.setHeader('Content-Type','text/plain');
	res.end('Bad Request');
}
function notFind(res) {
	res.statusCode = 404;
	res.setHeader('Content-Type','text/plain');
	res.end('Not Find');
}


server.listen('8000');